const app = getApp()
import { getStorage } from "../../utils/localStorage"
import { selectUserLabel, focusActivities, selectDynamics, activityGive_option, dynamiGive_option, labelAll, label_Server, dynamiCollection_option } from "../../api/homePage"
import { baseUrl } from "../../api/request"
import { year, month, day } from "../../utils/util"
import { getMapDistance } from "../../utils/address"
Component({
  data: {
    baseUrl: baseUrl,
    scFlag: false,
    playFlag: true,
    gzFlag: true,
    videoSrc: 'https://vd3.bdstatic.com/mda-kddgspkr9a6ms4e8/sc/mda-kddgspkr9a6ms4e8.mp4?v_from_s=hkapp-haokan-nanjing&auth_key=1663748357-0-0-030d97498352ecd58d667d85aeb7a04e&bcevod_channel=searchbox_feed&pd=1&cd=0&pt=3&logid=2957636016&vid=13803630037796894051&abtest=&klogid=2957636016',
    swiper: {
      autoplay: true, //自动切换
      dots: true, //指示点
      dotsColor: "#ffffff", //指示点颜色
      dotsActiveColor: "#4646A0", //选中指示点颜色
      circular: true, //衔接滑动
      duration: 3000, //滑动动画时长
      boxFlag: true,
    },
    listQuery: {
      labelId: 0,
      userId: getStorage('user').id,
      pageSize: 10,
      pageNum: 1,
    },
    total: 0, //列表总页数
    showPull: true, //上拉加载更多状态
    labelList: [],
    lbData: {},
    list: [],
    latlng: {},
    activityList: [], //获取信息列表
    UserDynamicsList: [], //用户动态列表
    labelFlag: false, //选择标签弹窗是否打开状态
    follwLabel: [], //关注的标签
    rendLabel: [], //推荐的标签
    textIndex: 0,
    optFlag: false, //标签操作状态
    pageTop: app.globalData.navHeight + app.globalData.navTop,
  },
  lifetimes: {
    attached() {
      if (app.loginState()) return;
      this.setData({
        user: getStorage("user"),
        latlng: getStorage("latLng"),
        "listQuery.userId": getStorage("user").id
      });
      this.getSelectUserLabel();
      this.getActivities_list();
      this.getUserDynamics_list();
    },
    detached() {
      this.setData({
        labelFlag: false
      });
    },
  },
  pageLifetimes: {
    show: function () {
      //动态点赞静态处理
      let dynamicId = app.globalData.dynamicId, dynamicGive = app.globalData.dynamicGive, dynamicGiveNum = app.globalData.dynamicGiveNum,
        dynamicCtion = app.globalData.dynamicCtion, dynamicCtionNum = app.globalData.dynamicCtionNum,
        dynamicMent = app.globalData.dynamicMent;
      if (dynamicId) {
        let index = this.data.UserDynamicsList.findIndex(item => { return item.id === dynamicId }),
          likeValue = "UserDynamicsList[" + index + "].likeState",
          likeNum = "UserDynamicsList[" + index + "].likeNumber",
          ctionValue = "UserDynamicsList[" + index + "].collectionState",
          ctionNum = "UserDynamicsList[" + index + "].collectionNumber",
          commentNum = "UserDynamicsList[" + index + "].commentNumber";
        this.setData({
          [likeValue]: dynamicGive === 1 ? true : false,
          [likeNum]: dynamicGiveNum,
          [ctionValue]: dynamicCtion === 1 ? true : false,
          [ctionNum]: dynamicCtionNum,
          [commentNum]: dynamicMent,
        });

      };
    }
  },
  methods: {
    //获取标签列表
    async getSelectUserLabel() {
      let res = await selectUserLabel({ userId: getStorage('user').id });
      res.data.data.unshift({ id: 0, labelName: '推荐' });
      this.setData({
        labelList: res.data.data
      });
    },
    //获取活动列表数据 
    getActivities_list() {
      let that = this.data;
      focusActivities({ userId: that.user.id }).then(res => {
        res.data.data.forEach(item => {
          item.imageScale = item.imageScale.split(",");
          item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
        });
        this.setData({
          activityList: res.data.data
        });
      });
    },
    //获取用户动态列表信息
    getUserDynamics_list() {
      let that = this.data;
      selectDynamics(that.listQuery).then(res => {
        res.data.rows.forEach(item => {
          item.imageScale = item.imageScale.split(",");
          item.randowNum = this.randomFun(0, (item.imageScale.length - 1));
          item.distance = getMapDistance(that.latlng.lat, that.latlng.lng, item.latitude, item.longitude);
        });
        this.setData({
          UserDynamicsList: [...that.UserDynamicsList, ...res.data.rows],
          total: Math.ceil(res.data.total / that.listQuery.pageSize)
        });
      });
    },
    //随机数
    randomFun(start, end) {
      return Math.round(Math.random() * (end - start) + start)
    },
    //banner点击事件
    bannerClick(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/bnnerDetailMore/index?id=' + item.id,
      })
    },
    //列表详情
    detail(e) {
      const item = e.currentTarget.dataset.item;
      wx.navigateTo({
        url: '/pagesShouYe/pages/listDetail/index?id=' + item.id + '&dynamicType=用户动态',
      })
    },
    //文字tab栏选择事件
    textEvent(e) {
      this.setData({
        UserDynamicsList: [],
        textIndex: e.detail.index,
        "listQuery.labelId": e.detail.data.id,
        "listQuery.pageSize": 10,
        "listQuery.pageNum": 1,
      });
      this.getUserDynamics_list();
    },
    //视频播放按钮事件
    video(e) {
      const flag = e.currentTarget.dataset.flag;
      const video = wx.createVideoContext('video');
      if (flag) {
        console.log('播放');
        this.setData({
          playFlag: !flag
        });
        video.play();
      } else {
        console.log('暂停');
        this.setData({
          playFlag: !flag
        });
        video.stop();
      }
    },
    //关注用户点击事件
    gzEvent(e) {
      const flag = e.currentTarget.dataset.flag;
      if (flag) {
        console.log('关注');
        this.setData({
          gzFlag: !flag
        })
      } else {
        console.log('取消关注');
        this.setData({
          gzFlag: !flag
        })
      }
    },
    //活动点赞图标事件
    async collectionClick(e) {
      let that = this.data;
      let item = e.currentTarget.dataset.item,
        i = e.currentTarget.dataset.index;
      let flag = !item.likeState ? true : false;
      activityGive_option({ userId: that.user.id, activityId: item.id, state: flag }).then(res => {
        let state = "activityList[" + i + "].likeState",
          index = "activityList[" + i + "].likeNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [index]: !flag ? item.likeNumber - 1 : item.likeNumber + 1
          });
        };
      });
    },
    //用户动态点赞或取消点赞事件
    commentClick(e) {
      let that = this.data,
        item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        flag = !item.likeState ? true : false;
      dynamiGive_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
        let state = "UserDynamicsList[" + index + "].likeState";
        let num = "UserDynamicsList[" + index + "].likeNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [num]: !item.likeState ? item.likeNumber + 1 : item.likeNumber - 1
          });
        };
      });
      // if (res.data.code === 200) {
      //     let colleStatus = "list[" + index + "].colleStatus";
      //     let colleNum = "list[" + index + "].colleNum";
      //     let scNum = 0;
      //     if (res.data.data === 1) {
      //         scNum = _this.list[index].colleNum + 1;
      //     } else {
      //         scNum = _this.list[index].colleNum - 1;
      //     };
      //     this.setData({
      //         [colleStatus]: res.data.data,
      //         [colleNum]: scNum,
      //     });
      // };
    },
    //用户动态收藏图标按钮事件
    scTap(e) {
      let that = this.data;
      let item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index,
        flag = !item.collectionState ? true : false;
      dynamiCollection_option({ userId: that.user.id, dynamicsId: item.id, state: flag }).then(res => {
        let state = "UserDynamicsList[" + index + "].collectionState",
          num = "UserDynamicsList[" + index + "].collectionNumber";
        if (res.data.code === 200) {
          wx.showToast({
            icon: 'none',
            title: res.data.msg,
            duration: 1000,
          })
          this.setData({
            [state]: flag,
            [num]: flag ? item.collectionNumber + 1 : item.collectionNumber - 1
          });
        };
      });
    },
    //标签栏右手的图标点击事件
    labelOpen() {
      this.setData({
        labelFlag: true
      });
      let followArr = [], rendArr = [];
      labelAll({ userId: this.data.user.id }).then(res => {
        res.data.data.forEach(item => {
          if (item.flagLabel) {
            followArr.push(item);
          } else {
            rendArr.push(item);
          };
        });
        this.setData({
          follwLabel: followArr, //关注的标签
          rendLabel: rendArr,
        });
        console.log(res, 'allLabel');
      });
    },
    //关闭标签操作弹窗
    labelClose() {
      this.setData({
        labelFlag: false,
      });
    },
    //标签删除事件
    labelRemove(e) {
      let that = this.data,
        item = e.currentTarget.dataset.item,
        rendArr = that.rendLabel,
        followArr = that.follwLabel.filter(val => val.id != item.id);
      rendArr.push(item);
      this.setData({
        follwLabel: followArr,
        rendLabel: rendArr
      });
    },
    //添加标签
    labelAdd(e) {
      let that = this.data,
        item = e.currentTarget.dataset.item,
        followArr = that.follwLabel, rendArr = [];
      followArr.push(item);
      rendArr = that.rendLabel.filter(val => val.id != item.id);
      this.setData({
        follwLabel: followArr,
        rendLabel: rendArr,
        optFlag: true,
      });

    },
    //我关注的标签点击事件
    labelTz(e) {
      let item = e.currentTarget.dataset.item,
        index = e.currentTarget.dataset.index;
      if (this.data.optFlag === false) {
        this.setData({
          UserDynamicsList: [],
          textIndex: index + 1,
          "listQuery.labelId": item.id,
          "listQuery.pageNum": 1,
          labelFlag: false,

        });
        this.getUserDynamics_list();
      };

    },
    //点击保存事件
    pationClick(e) {
      let that = this.data,
        arr = [];
      if (that.optFlag) {
        that.follwLabel.forEach(item => {
          arr.push(item.id);
        });
        if (that.follwLabel.length != 0) {
          label_Server({ userId: that.user.id, labelId: arr.join(",") }).then(res => {
            if (res.data.code === 200) {
              this.setData({
                optFlag: false,
                labelFlag: false,
                textIndex: that.follwLabel.length
              });
              this.getSelectUserLabel();
            }
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: '我关注的乡音不能为空!!!',
          });
        };
      } else {
        this.setData({
          optFlag: true
        });
      };
    },
    /* 上拉加载更多 */
    pullUp(e) {
      let that = this.data;
      if ((that.listQuery.pageNum + 1) <= that.total) {
        this.setData({
          showPull: false,
          "listQuery.pageNum": that.listQuery.pageNum += 1
        });
        this.getUserDynamics_list();
      } else {
        this.setData({
          showPull: true
        });
      };
    },
  },
})